package com.sywb.chuangyebao.view.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.view.BusinessDetailsActivity;

import org.bining.footstone.log.Logger;
import org.bining.footstone.utils.ToastUtils;
import org.bining.footstone.widget.ProgressWebView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页-商城
 */
public class WebFragment extends BaseStatisticsFragment {

    protected RelativeLayout actionbar;
    private ImageView actionbarBack;
    private ImageView actionbarTips;
    private TextView actionbarTitle;
    private LinearLayout actionbarMenu;
    private View actionbarBottomLine;
    private ProgressWebView commonWebview;

    private int type;
    private String loadUrl;

    private List<String> urlList;
    private int index;

    /**
     * Fragment 实例
     */
    public static WebFragment newInstance(Object... pramars) {
        WebFragment fragment = new WebFragment();
        fragment.setArguments(getBundle(pramars));
        return fragment;
    }

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.layout_malll;
    }

    @Override
    public void initView(View view, Bundle bundle) {
        super.initView(view, bundle);
        if (bundle == null) {
            type = getArguments().getInt("p0", 0);
            loadUrl = getArguments().getString("p1", "");
            index = getArguments().getInt("p3");
        } else {
            type = bundle.getInt("p0", 0);
            loadUrl = bundle.getString("p1", "");
        }
        actionbar = (RelativeLayout) getView(R.id.actionbar);
        actionbarBack = (ImageView) getView(R.id.actionbar_back);
        actionbarTips = (ImageView) getView(R.id.actionbar_tips);
        actionbarTitle = (TextView) getView(R.id.actionbar_title);
        actionbarMenu = (LinearLayout) getView(R.id.actionbar_menu);
        actionbarBottomLine = (View) getView(R.id.actionbar_bottom_line);
        commonWebview = (ProgressWebView) getView(R.id.common_webview);

        switch (type) {
            case 1:
                actionbar.setVisibility(View.GONE);
                actionbarTitle.setText("创业项目");
                actionbarBack.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        if (commonWebview.canGoBack()) {
//                            commonWebview.goBack();
//                        } else {
//                            commonWebview.loadUrl(loadUrl);
//                        }

                        if (urlList.size() > 1) {
                            commonWebview.loadUrl(urlList.get(urlList.size() - 2));
                            urlList.remove(urlList.size() - 1);
                            if (urlList.size() <= 1) {
                                actionbarBack.setVisibility(View.GONE);
                            }
                        } else {
                            urlList.clear();
                            urlList.add(loadUrl);
                            commonWebview.loadUrl(loadUrl);
                            actionbarBack.setVisibility(View.GONE);
                        }
                    }
                });
                break;
            case 2:
                actionbar.setVisibility(View.GONE);
                break;
            case 3:
                actionbar.setVisibility(View.GONE);
                break;
            default:
                actionbar.setVisibility(View.GONE);
                break;
        }

        urlList = new ArrayList<>();
        urlList.add(loadUrl);

        actionbarBack.setVisibility(View.GONE);
        initWebView();
    }

    @Override
    public void initPresenter() {
        switch (type) {
            case 3:
                setHtml(loadUrl);
                break;
            default:
                commonWebview.loadUrl(loadUrl);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt("p0", type);
        outState.putString("p1", loadUrl);
        outState.putInt("p3", index);
        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean useRxBus() {
        return false;
    }

    /**
     * 初始化WebView
     */
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        /**
         * setAllowFileAccess 启用或禁止WebView访问文件数据 setBlockNetworkImage 是否显示网络图像
         * setBuiltInZoomControls 设置是否支持缩放 setCacheMode 设置缓冲的模式
         * setDefaultFontSize 设置默认的字体大小 setDefaultTextEncodingName 设置在解码时使用的默认编码
         * setFixedFontFamily 设置固定使用的字体 setJavaSciptEnabled 设置是否支持Javascript
         * setLayoutAlgorithm 设置布局方式 setLightTouchEnabled 设置用鼠标激活被选项
         * setSupportZoom 设置是否支持变焦
         * */
        WebSettings settings = commonWebview.getSettings();
        settings.setJavaScriptEnabled(true);// 设置支持javascript脚本
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 1.NARROW_COLUMNS：可能的话使所有列的宽度不超过屏幕宽度；2.NORMAL：正常显示不做任何渲染；3.SINGLE_COLUMN：把所有内容放大webview等宽的一列中
        // settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);// 排版适应屏幕
        settings.setDisplayZoomControls(false);
        settings.setAllowFileAccess(true); // 启用或禁止WebView访问文件数据
        settings.setBuiltInZoomControls(false); //  隐藏缩放按钮
        settings.setSupportZoom(true); // 支持缩放
        // settings.setUseWideViewPort(true);// 可任意比例缩放
        settings.setLoadWithOverviewMode(true);//setUseWideViewPort方法设置webview推荐使用的窗口；设置webview加载的页面的模式
        settings.setGeolocationEnabled(true);// 启用地理定位
        settings.setDomStorageEnabled(true);
        settings.setSaveFormData(true);// 保存表单数据
        // settings.setSavePassword(true);
        // settings.setTextZoom(200);
        // settings.setMixedContentMode(1);
//         settings.setAcceptThirdPartyCookies();
        settings.setAllowFileAccess(true);
        settings.setAllowContentAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);

        commonWebview.setWebChromeClient(new WebChromeClient());
        // commonWebview.requestDisallowInterceptTouchEvent(true);
        commonWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Logger.e("shouldOverrideUrlLoading:" + url);

                urlList.add(url);
                if (urlList.size() > 1) {
                    actionbarBack.setVisibility(View.VISIBLE);
                } else {
                    actionbarBack.setVisibility(View.GONE);
                }

                // 如下方案可在非微信内部WebView的H5页面中调出微信支付
                if (url.startsWith("https://wx.tenpay.com")) {
//                    Intent intent = new Intent();
//                    intent.setAction(Intent.ACTION_VIEW);
//                    intent.setData(Uri.parse(url));
//                    startActivity(intent);
//                    return true;
                    Map<String, String> extraHeaders = new HashMap<String, String>();
                    extraHeaders.put("Referer", "http://dh.3158.cn/index/order/notify/");
                    view.loadUrl(url, extraHeaders);
                } else if (url.startsWith("weixin://wap/pay?")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                } else {
                    view.loadUrl(url);
                }
                return false;
            }
        });
    }

    /**
     * 设置需展示的Html片段
     */
    private void setHtml(String protocol) {
        if (protocol != null) {
            commonWebview.getSettings().setDefaultTextEncodingName("utf-8");
            commonWebview.loadDataWithBaseURL("http://www.3158.cn", protocol, "text/html", "UTF-8", null);
        } else {
            ToastUtils.show(mActivity, "未获取到内容，请稍后重试");
        }
    }

    @Override
    public String getStatisticsIdentity() {
        return type == 1 ? "创业项目" : "兑换商场";
    }
}
